package com.basker.pisces.core.query.factory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;

import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.basker.pisces.core.meta.bean.BeanFieldDescriptor;
import com.basker.pisces.domain.annotation.Condition;
import com.basker.pisces.domain.annotation.PageIndex;
import com.basker.pisces.domain.annotation.PageSize;
import com.basker.pisces.domain.annotation.PropertyOutput;
import com.basker.pisces.utils.NumberUtils;

/**
 * 该构建器可以通过POJO对象+注解的方式，快速构建一个{@link SimpleQueryInfo}对象
 *
 * @author hangwen
 * @see SimpleQueryInfo
 * @see PageSize
 * @see PageIndex
 * @see Condition
 */
public class SimpleQueryInfoBuilder {
    public static SimpleQueryInfoBuilder create() {
        return new SimpleQueryInfoBuilder(new SimpleQueryInfo());
    }

    public static SimpleQueryInfoBuilder create(SimpleQueryInfo simpleQueryInfo) {
        return new SimpleQueryInfoBuilder(simpleQueryInfo);
    }

    private SimpleQueryInfo simpleQueryInfo;

    private SimpleQueryInfoBuilder(SimpleQueryInfo simpleQueryInfo) {
        this.simpleQueryInfo = simpleQueryInfo;
    }

    /**
     * 将输出对象的类型填充到SimpleQueryInfo，可以从中获取需要查询的字段
     *
     * @param outputType，支持的注解有：{@link PropertyOutput}
     * @return
     */
    public SimpleQueryInfoBuilder fillQueryRequest(Class<?> outputType) {
        Assert.notNull(outputType, "parameter 'outputType' is required");

        BeanFieldDescriptor[] beanFieldDescriptors = BeanFieldDescriptor.getBeanFieldDescriptors(outputType);
        for (BeanFieldDescriptor beanFieldDescriptor : beanFieldDescriptors) {
            this.addSelectField(beanFieldDescriptor);
        }

        return this;
    }

    /**
     * 将一个POJO对象填充到SimpleQueryInfo中，可以从中获取分页信息和条件
     *
     * @param inputObject，支持的注解有：{@link PageSize}，{@link PageIndex}，{@link Condition}
     * @return
     */
    public SimpleQueryInfoBuilder fillQueryRequest(Object inputObject) {
        Assert.notNull(inputObject, "parameter 'input' is required");

        // 映射条件的字段
        List<BeanFieldDescriptor> conditionFieldDescriptors = new ArrayList<>();

        for (BeanFieldDescriptor beanFieldDescriptor : BeanFieldDescriptor
                .getBeanFieldDescriptors(inputObject.getClass())) {
            // 读取pageSize的值
            if (resolvePageSize(inputObject, beanFieldDescriptor)) {
                continue;
            }

            // 读取pageIndex的值
            if (resolvePageIndex(inputObject, beanFieldDescriptor)) {
                continue;
            }

            // 获取条件字段
            Condition condition = beanFieldDescriptor.getAnnotation(Condition.class);
            if (condition != null) {
                conditionFieldDescriptors.add(beanFieldDescriptor);
            }
        }

        if (!CollectionUtils.isEmpty(conditionFieldDescriptors)) {
            this.resolveConditions(inputObject, conditionFieldDescriptors);
        }

        return this;
    }

    public SimpleQueryInfo simpleQueryInfo() {
        return simpleQueryInfo;
    }

    private void addSelectField(BeanFieldDescriptor beanFieldDescriptor) {
        PropertyOutput propertyOutput = beanFieldDescriptor.getAnnotation(PropertyOutput.class);
        if (propertyOutput == null) {
            return;
        }

        String propertyAlias = this.getPropertyAlias(beanFieldDescriptor, propertyOutput);
        this.simpleQueryInfo.addSelectFields(propertyAlias);
    }

    private String getPropertyAlias(BeanFieldDescriptor beanFieldDescriptor, Condition condition) {
        String propertyAlias = condition.propertyAlias();

        if (StringUtils.isEmpty(propertyAlias)) {
            propertyAlias = beanFieldDescriptor.getName();
        }

        return propertyAlias;
    }

    private String getPropertyAlias(BeanFieldDescriptor beanFieldDescriptor, PropertyOutput propertyOutput) {
        String propertyAlias = propertyOutput.value();
        if (StringUtils.isEmpty(propertyAlias)) {
            propertyAlias = propertyOutput.propertyAlias();
        }

        if (StringUtils.isEmpty(propertyAlias)) {
            propertyAlias = beanFieldDescriptor.getName();
        }

        return propertyAlias;
    }

    private boolean isEmptyValue(Object value) {
        if (value == null) {
            return true;
        }

        if (value instanceof String) {
            return StringUtils.isEmpty(value);
        }

        if (value instanceof Collection<?>) {
            return ((Collection<?>) value).isEmpty();
        }

        return false;
    }

    private boolean resolveCondition(Object input, BeanFieldDescriptor beanFieldDescriptor,
                                     Set<String> exclusiveConditions) {
        Condition condition = beanFieldDescriptor.getAnnotation(Condition.class);
        if (condition == null) {
            return false;
        }

        String propertyAlias = this.getPropertyAlias(beanFieldDescriptor, condition);
        if (exclusiveConditions.contains(propertyAlias)) {
            return false;
        }

        Object value = beanFieldDescriptor.getValue(input);
        if (!this.isEmptyValue(value)) {
            String operator = condition.operator();
            this.simpleQueryInfo.addCondition(propertyAlias, operator, value);

            String[] exclusive = condition.exclusive();
            if (exclusive.length > 0) {
                exclusiveConditions.addAll(Arrays.asList(exclusive));
            }
        }

        return true;
    }

    private void resolveConditions(Object inputObject, List<BeanFieldDescriptor> conditionFieldDescriptors) {
        // 对conditionFieldDescriptors的流按priority排序
        Stream<BeanFieldDescriptor> sortedStream = conditionFieldDescriptors.stream().sorted(Comparator
                .comparingInt(beanFieldDescriptor -> beanFieldDescriptor.getAnnotation(Condition.class).priority()));
        Set<String> exclusiveConditions = new HashSet<>();

        sortedStream.forEach(beanFieldDescriptor -> {
            this.resolveCondition(inputObject, beanFieldDescriptor, exclusiveConditions);
        });
    }

    private boolean resolvePageIndex(Object input, BeanFieldDescriptor beanFieldDescriptor) {
        PageIndex pageIndex = beanFieldDescriptor.getAnnotation(PageIndex.class);
        if (pageIndex == null) {
            return false;
        }

        Object pageIndexValue = beanFieldDescriptor.getValue(input);
        if (pageIndexValue != null) {
            this.simpleQueryInfo.setPageIndex(NumberUtils.parseInt(pageIndexValue));
        }

        return true;
    }

    private boolean resolvePageSize(Object input, BeanFieldDescriptor beanFieldDescriptor) {
        PageSize pageSize = beanFieldDescriptor.getAnnotation(PageSize.class);
        if (pageSize == null) {
            return false;
        }

        Object pageSizeValue = beanFieldDescriptor.getValue(input);
        if (pageSizeValue != null) {
            this.simpleQueryInfo.setPageSize(NumberUtils.parseInt(pageSizeValue));
        }

        return true;
    }
}
